<template>
  <view>
    <!-- 第负一个内容 , 弹框提示先去登录 -->
    <u-popup
      v-model="isLoginShow"
      mode="center"
      border-radius="14"
      width="600rpx"
      height="300rpx"
      :mask-close-able="false"
    >
      <view class="tick-button">
        <u-button
          :ripple="true"
          shape="square"
          size="medium"
          @click="gotoLoginPage"
          >你还未登录, 请先登录^_^</u-button
        >
      </view>
    </u-popup>

    <!-- 第零个内容 , 弹框提示选择美食记录还是运动消耗 -->
    <u-popup
      v-model="isPopupShow"
      mode="center"
      border-radius="14"
      width="600rpx"
      height="300rpx"
    >
      <view class="tick-button">
        <u-button
          :ripple="true"
          shape="square"
          size="medium"
          @click="gotoAddPageByFoodId"
          >添加饮食</u-button
        >
        <u-button
          :ripple="true"
          shape="square"
          size="medium"
          @click="gotoAdd2PageByFoodId"
          >运动消耗</u-button
        >
      </view>
    </u-popup>

    <!-- <view class="healthy">健康助手</view> -->
    <!-- <canvas id="myChart" style="width: 100%; height: 300px"></canvas> -->
    <!-- #ifdef H5 -->
    <!-- <canvas id="myChart" type="webgl" canvas-id="myChart" ref="myChart"></canvas> -->
    <!-- #endif -->

    <!-- 第一个内容 -->
    <view class="content1">
      <!-- #ifdef MP -->
      <!-- <view class="charts-box">
        <qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
      </view> -->
      <!-- #endif -->

      <view class="content11">
        <view class="yssr">饮食摄入</view>
        <view class="ysdata">{{ yssr }}</view>
        <view class="ysqk">千卡</view>
      </view>

      <view class="content12">
        <view class="hksr">{{ hksr < 0 ? "多摄入了" : "还可摄入" }}</view>
        <view class="srdata">{{ Math.abs(hksr) }}</view>
        <view class="tjsr">推荐摄入{{ tjsr }}</view>
      </view>

      <view class="content13">
        <view class="ydxh">运动消耗</view>
        <view class="yddata">{{ ydxh }}</view>
        <view class="ydqk">千卡</view>
      </view>

      <u-line-progress
        :active-color="hksr < 0 ? '#ff838b' : '#b3df63'"
        :percent="percentage"
        :show-percent="false"
        :round="false"
      ></u-line-progress>
    </view>

    <!-- 第二个内容 -->
    <!-- <view class="content2">
	   	   <view class="content21">
	   			   <view class="ts">碳水</view>
				   
	   			   <view class="progress-box">
	   			   		<progress :percent="pgList[0]" activeColor="#10AEFF" stroke-width="20rpx"  border-radius="50rpx"/>
	   			   </view>
				   
	   			   <view class="tsdata">0<span>/153克</span></view>
	   		   </view>
	   		   
	   		   <view class="content22">
	   		   		<view class="dbz">蛋白质</view>
					
	   		   		<view class="progress-box">
	   		   				<progress :percent="pgList[1]" activeColor="#10AEFF" stroke-width="20rpx"  border-radius="50rpx"/>
	   		   		</view>
					
	   		   		<view class="dbzdata">0<span>/61克</span></view>
	   		   </view>
	   		   
	   		   <view class="content23">
	   		   		<view class="zf">脂肪</view>
					
	   		   		<view class="progress-box">
	   		   				<progress :percent="pgList[2]" activeColor="#10AEFF" stroke-width="20rpx"  border-radius="50rpx"/>
	   		   		</view>
					
	   		   		<view class="zfdata">0<span>/41克</span></view>
	   		   </view>
	   </view> -->

    <!-- 第三个内容 -->
    <view class="tjfood" @click="gotoPageByFoodId">+ 添加饮食/运动消耗</view>

    <!-- 第四个内容 -->
    <view class="noFood" v-show="!isShowFoodRecords && !isShowSportRecords">
      <image
        :src="`${urlImg}/food/icon/1.png`"
        mode=""
        class="noFoodphoto"
      ></image>

      <view class="noFoodTx">
        暂无饮食记录<br />
        <span>请点击上方按钮记录三餐,完整记录三餐,分析才准确</span>
      </view>
    </view>

    <!-- 第五个内容 -->
    <view class="foods" v-show="isShowFoodRecords">
      <view class="foodtitle">
        <view class="foodphoto">
          <image
            :src="`${urlImg}/food/icon/饮食.png`"
            mode=""
            class="foodphoto"
          ></image>
        </view>
        <view class="foodname">饮食</view>
        <view class="fooddata"
          >{{ yssr }}<span>千卡</span></view
        >
      </view>

      <view
        class="foodcontent"
        v-for="item in calorieAddRecordsArray"
        :key="item.id"
      >
        <view class="foodcontents" v-text="item.foodName">鸡蛋1个</view>
        <view class="foodcontentdata" v-text="item.totalCalorie + '千卡'"
          >92千卡</view
        >
        <view class="sc">
          <image
            :src="`${urlImg}/food/icon/返回右.png`"
            mode=""
            class="sc"
          ></image>
        </view>
      </view>
    </view>

    <!-- 第六个内容 -->
    <view class="foods" v-show="isShowSportRecords">
      <view class="foodtitle">
        <view class="foodphoto">
          <image
            :src="`${urlImg}/food/icon/运动.png`"
            mode=""
            class="foodphoto"
          ></image>
        </view>
        <view class="foodname">运动</view>
        <view class="fooddata">{{ ydxh }}<span>千卡</span></view>
      </view>

      <view
        class="foodcontent"
        v-for="item in calorieReduceRecordsArray"
        :key="item.id"
      >
        <view class="foodcontents" v-text="item.foodName">鸡蛋1个</view>
        <view class="foodcontentdata" v-text="item.totalCalorie + '千卡'"
          >92千卡</view
        >
        <view class="sc">
          <image
            :src="`${urlImg}/food/icon/返回右.png`"
            mode=""
            class="sc"
          ></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
// import * as echarts from 'echarts';

export default {
  data() {
    return {
      pgList: [10, 20, 30],
      yssr: "0",
      hksr: "0",
      tjsr: "0",
      ydxh: "0",
      calorieAddRecordsArray: [], // 饮食摄入
      calorieReduceRecordsArray: [], // 运动消耗
      isPopupShow: false, // 运动
      isLoginShow: false,

      categoriesRate: 0,

      urlImg: "",

      // ucharts 相关配置
      chartData: {},
      //您可以通过修改 config-ucharts.js 文件中下标为 ['gauge'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
      opts: {
        color: [
          "#1890FF",
          "#91CB74",
          "#FAC858",
          "#EE6666",
          "#73C0DE",
          "#3CA272",
          "#FC8452",
          "#9A60B4",
          "#ea7ccc",
        ],
        padding: undefined,
        title: {
          name: "",
          fontSize: 25,
          color: "#2fc25b",
          offsetY: 0,
        },
        subtitle: {
          name: "",
          fontSize: 15,
          color: "#1890ff",
          offsetY: 0,
        },
        extra: {
          gauge: {
            type: "default",
            width: 24,
            labelColor: "#666666",
            startAngle: 0.85,
            endAngle: 0.15,
            startNumber: 0,
            endNumber: 200,
            labelFormat: "",
            splitLine: {
              fixRadius: -10,
              splitNumber: -1,
              width: 15,
              color: "#FFFFFF",
              childNumber: -1,
              childWidth: 12,
            },
            pointer: {
              width: 0,
              color: "auto",
            },
          },
        },
      },
    };
  },
  methods: {
    ...mapActions("moduleCommon", ["updateUserId"]),

    // 跳转到登录页面
    gotoLoginPage() {
      uni.reLaunch({
        url: `/pages/dl/dl`,
      });
    },
    // 跳转到add页面
    gotoAddPageByFoodId() {
      this.isPopupShow = false;
      uni.navigateTo({
        url: `/pages/add/add`,
        success: (res) => {
          // console.log(res);
        },
        fail: (err) => {
          // console.log(err);
        },
      });
    },
    // 跳转到add2页面
    gotoAdd2PageByFoodId() {
      this.isPopupShow = false;
      uni.navigateTo({
        url: `/pages/addSport/addSport`,
        success: (res) => {
          // console.log(res);
        },
        fail: (err) => {
          // console.log(err);
        },
      });
    },
    // 弹窗选择
    gotoPageByFoodId() {
      // console.log('', new Date());
      this.isPopupShow = true;
      // console.log('', new Date());
    },
    // 获取Calorie信息
    getCalorieInfo() {
      const {
        hostname,
        comment: { userId },
      } = this.$store.state.moduleCommon;
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${hostname}/api/Calories/user/calories/${userId}`,
          method: "GET",
          success: ({
            data: {
              data: {
                addCalorie,
                reduceCalorie,
                availableCalories,
                totalCalorie,
              },
            },
          }) => {
            this.yssr = addCalorie; // 饮食摄入
            this.ydxh = reduceCalorie; // 运动消耗
            this.hksr = availableCalories; // 还可摄入
            this.tjsr = totalCalorie; // 推荐摄入

            this.categoriesRate = Math.abs((this.tjsr - this.hksr) / this.tjsr);
            // console.log("this.categoriesRate0", this.categoriesRate);
            resolve();
          },
          fail: (err) => {
            console.log(err);
          },
        });
      });
    },
    // 获取Calorie的美食记录, 运动消耗
    getCalorieRecords() {
      // 使用函数解构获取对应的参数
      const {
        hostname,
        comment: { userId },
      } = this.$store.state.moduleCommon;

      uni.request({
        url: `${hostname}/api/Calories/user/records/calories/${userId}`,
        method: "GET",
        success: ({
          data: {
            data: { dietIntake, exerciseExpenditure },
          },
        }) => {
          this.calorieAddRecordsArray = dietIntake;
          this.calorieReduceRecordsArray = exerciseExpenditure;
          // console.log("calorieAddRecordsArray", this.calorieAddRecordsArray);
          // console.log("calorieReduceRecordsArray", this.calorieReduceRecordsArray);
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },
    // H5 仪表盘 echarts
    showCanvas() {
      // 使用DOM? 小程序不能使用DOM
      var chartDom = document.getElementById("myChart");

      // 换成$refs? 小程序也不支持
      // https://zh.uniapp.dcloud.io/tutorial/vue3-api.html#%E5%AE%9E%E4%BE%8B-property
      // var chartDom = this.$refs.myChart.$el;

      // console.log('myChart', chartDom);
      // console.log('123456', this.$refs.myChart);

      var myChart = echarts.init(chartDom);
      var option;

      option = {
        series: [
          {
            type: "gauge",
            center: ["50%", "60%"],
            startAngle: 200,
            endAngle: -20,
            min: 0,
            max: this.tjsr,
            splitNumber: 12,
            itemStyle: {
              color: "#b3df63",
            },
            progress: {
              show: true,
              width: 30,
            },
            pointer: {
              show: false,
            },
            axisLine: {
              lineStyle: {
                width: 30,
              },
            },
            axisTick: {
              show: false,
              distance: -45,
              splitNumber: 5,
              lineStyle: {
                width: 2,
                color: "#999",
              },
            },
            splitLine: {
              show: false,
              distance: -52,
              length: 14,
              lineStyle: {
                width: 3,
                color: "#999",
              },
            },
            axisLabel: {
              show: false,
              distance: -20,
              color: "#999",
              fontSize: 20,
            },
            anchor: {
              show: false,
            },
            title: {
              show: false,
            },
            detail: {
              valueAnimation: true,
              width: "60%",
              lineHeight: 40,
              borderRadius: 8,
              offsetCenter: [0, "-15%"],
              fontSize: 40,
              fontWeight: "bolder",
              formatter: "{value}",
              color: "inherit",
              show: false,
            },
            data: [
              {
                value: 0,
              },
            ],
          },
        ],
      };
      setInterval(() => {
        // const random = +(Math.random() * 60).toFixed(2);
        // console.log(this.hksr, this.tjsr);
        const random = this.tjsr - this.hksr;
        myChart.setOption({
          series: [
            {
              data: [
                {
                  value: random,
                },
              ],
            },
            {
              data: [
                {
                  value: random,
                },
              ],
            },
          ],
        });

        /* if (this.hksr < 200) {
          myChart.setOption({
            series: [
              {
                itemStyle: {
                  color: "#fe858a",
                },
              },
            ],
          });
        } */
      }, 2000);

      option && myChart.setOption(option);
    },
    // MP 仪表盘 ucharts
    getServerData() {
      //模拟从服务器获取数据时的延时
      setTimeout(() => {
        // console.log('this.categoriesRate1', this.categoriesRate);
        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
        let res = {
          categories: [
            { value: this.categoriesRate, color: "#b3df63" },
            { value: 1, color: "#e6ebf8" },
          ],
          series: [
            {
              name: "完成率",
              data: 0,
            },
          ],
        };
        this.chartData = JSON.parse(JSON.stringify(res));
      }, 500);
    },
  },
  onReady() {
    const { urlImg } = this.$store.state.moduleCommon;
    this.urlImg = urlImg;
    // console.log("urlImg", urlImg);
    // H5, 由于微信小程序不支持原生DOM
    // #ifdef H5
    // this.showCanvas();
    // #endif

    // var chartDom = document.getElementById("myChart");
    // console.log('chartDom', chartDom);

    // console.log('this1', this.$el);
  },
  async onShow() {
    // 获取localStorage
    const Authorization = uni.getStorageSync("Authorization");
    if (Authorization) {
      this.isLoginShow = false;
      debugger;
      // 解析localStorage获取userId, 解析失败
      await this.updateUserId();
      debugger;
      // localStorage
      let Authorization2 = uni.getStorageSync("Authorization");
      // console.log('Authorization2', Authorization2);

      if (
        !Authorization2 &&
        typeof Authorization2 !== "undefined" &&
        Authorization2 != 0
      ) {
        // console.log('Authorization2是null', Authorization2);
        this.isLoginShow = true;
        return;
      }

      const {
        comment: { userId },
      } = this.$store.state.moduleCommon;
      debugger;
      console.log("userId", userId);
      if (userId === 0) {
        this.isLoginShow = true;
        return;
      }

      await this.getCalorieInfo();
      this.getCalorieRecords();
    } else {
      this.isLoginShow = true;
    }

    // #ifdef MP
    // 适配性不太行...
    // this.getServerData();
    // #endif
  },
  computed: {
    isShowFoodRecords() {
      return this.calorieAddRecordsArray.length > 0;
    },
    isShowSportRecords() {
      return this.calorieReduceRecordsArray.length > 0;
    },
    percentage() {
      return parseFloat((this.categoriesRate * 100).toFixed(2));
    },
  },
};
</script>

<style lang="scss" scoped>
view {
  vertical-align: middle;
}
page {
  background-color: rgb(250, 250, 250);
}

.healthy {
  width: 40%;
  height: 70rpx;
  text-align: center;
  margin: 0 auto;
  margin-top: 10rpx;
  font-size: 40rpx;
  line-height: 70rpx;
  background: rgb(255, 255, 255);
  border-radius: 50rpx;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.content1 {
  position: relative;
  width: 90%;
  height: 250rpx;
  margin: 0 auto;
  border: 1px solid gainsboro;
  border-radius: 20rpx 20rpx 0 0;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-top: 30rpx;
  .content11 {
    width: 20%;
    height: 130rpx;
    // background-color: royalblue;
    display: inline-block;
    line-height: 45rpx;
    margin-right: 10rpx;
    padding-left: 20rpx;
    margin-top: 70rpx;
    .ysdata {
      font-size: 40rpx;
    }
    .ysqk {
      color: rgb(165, 165, 165);
    }
  }
  .content12 {
    width: 55%;
    height: 210rpx;
    // background-color: royalblue;
    display: inline-block;
    margin-right: 10rpx;
    margin-top: 5rpx;
    .hksr,
    .srdata,
    .tjsr {
      text-align: center;
      line-height: 60rpx;
      font-size: 25rpx;
    }
    .hksr {
      margin-top: 40rpx;
    }
    .srdata {
      /* #ifdef H5 */
      color: #b3df63;
      font-weight: bolder;
      /* #endif */
      /* #ifdef MP */

      /* #endif */

      font-size: 72rpx;
    }
    .tjsr {
      color: gainsboro;
    }
  }
  .content13 {
    width: 20%;
    height: 130rpx;
    // background-color: royalblue;
    display: inline-block;
    line-height: 45rpx;
    margin-top: 70rpx;
    .ydxh {
      padding-left: 14%;
    }
    .yddata {
      text-align: right;
      font-size: 40rpx;
      padding-right: 10%;
      // padding-left: 68%;
    }
    .ydqk {
      color: rgb(165, 165, 165);
      padding-left: 50%;
    }
  }
}

//
.content2 {
  width: 90%;
  height: 150rpx;
  margin: 0 auto;
  border: 1px solid gainsboro;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-top: 10rpx;
  padding-top: 10rpx;
  .content21 {
    width: 30%;
    height: 130rpx;
    // background-color: royalblue;
    display: inline-block;
    line-height: 45rpx;
    margin-right: 5%;
    margin-top: 10rpx;
    padding-left: 20rpx;
    .ts {
      font-size: 30rpx;
    }
    .progress-box {
      width: 150rpx;
      margin-top: 5rpx;
    }
    .tsdata span {
      color: rgb(181, 181, 181);
    }
    .tsdata {
      margin-top: 5rpx;
      font-size: 30rpx;
    }
  }
  .content22 {
    width: 30%;
    height: 130rpx;
    // background-color: royalblue;
    display: inline-block;
    line-height: 45rpx;
    margin-right: 5%;
    margin-top: 10rpx;
    padding-left: 20rpx;
    .dbz {
      font-size: 30rpx;
    }
    .progress-box {
      width: 150rpx;
      margin-top: 5rpx;
    }
    .dbzdata span {
      color: rgb(181, 181, 181);
    }
    .dbzdata {
      margin-top: 5rpx;
      font-size: 30rpx;
    }
  }
  .content23 {
    width: 25%;
    height: 130rpx;
    // background-color: royalblue;
    display: inline-block;
    line-height: 45rpx;
    margin-right: 5%;
    margin-top: 10rpx;
    padding-left: 28rpx;
    .zf {
      font-size: 30rpx;
    }
    .progress-box {
      width: 150rpx;
      margin-top: 5rpx;
    }
    .zfdata span {
      color: rgb(181, 181, 181);
    }
    .zfdata {
      margin-top: 5rpx;
      font-size: 30rpx;
    }
  }
}

//
.tjfood {
  width: 90%;
  // width: 670rpx;
  height: 90rpx;
  margin: 0 auto;
  border: 1px solid gainsboro;
  border-radius: 20rpx;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-top: 30rpx;
  font-size: 40rpx;
  text-align: center;
  line-height: 90rpx;
  background: rgb(255, 255, 255);
  margin-top: 60rpx;
}

//
.noFood {
  width: 90%;
  height: 500rpx;
  margin: 0 auto;
  margin-top: 30rpx;
  font-size: 40rpx;
  text-align: center;
  line-height: 72rpx;
  background: rgb(250, 250, 250);
  margin-top: 60rpx;
  .noFoodphoto {
    background-size: 50rpx;
    width: 400rpx;
    height: 300rpx;
  }
  .noFoodTx {
    height: 100rpx;
    line-height: 50rpx;
    font-size: 32rpx;
    span {
      color: rgb(165, 165, 165);
      font-size: 30rpx;
    }
  }
}

//
.foods {
  width: 90%;
  //   height: 300rpx;
  margin: 0 auto;
  border: 1px solid gainsboro;
  border-radius: 20rpx;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  font-size: 40rpx;
  text-align: center;
  line-height: 90rpx;
  background: rgb(255, 255, 255);
  margin-top: 60rpx;
  .foodtitle {
    height: 50%;
    border-bottom: 5rpx solid gainsboro;
    line-height: 140rpx;
    .foodphoto {
      width: 100rpx;
      height: 88rpx;
      display: inline-block;
      // background: firebrick;
      line-height: 80rpx;
    }

    .foodname {
      width: 30%;
      display: inline-block;
      // background: red;
      text-align: left;
      font-weight: 600;
    }
    .fooddata {
      width: 53%;
      display: inline-block;
      // background: blue;
      padding-left: 110rpx;
      font-size: 32rpx;
    }
    .fooddata span {
      color: rgb(181, 181, 181);
    }
  }
  .foodcontent {
    height: 50%;
    line-height: 140rpx;
    .foodcontents {
      width: 50%;
      display: inline-block;
      // background: red;
      text-align: left;
      padding-left: 15rpx;
    }
    .foodcontentdata {
      width: 30%;
      display: inline-block;
      // background: red;
      margin-left: 5%;
      padding-left: 70rpx;
      font-size: 32rpx;
      color: rgb(181, 181, 181);
    }
    .sc {
      width: 40rpx;
      height: 35rpx;
      display: inline-block;
      // background: red;
      line-height: 35rpx;
    }
  }
}

.tick-button {
  text-align: center;
  margin-top: 90rpx;
  ::v-deep .u-size-medium {
    height: 120rpx;
  }
}

#myChart {
  width: 80%;
  height: 300px;
  transform: translateX(-36.5%) scale(0.7); /* 缩放比例，此处为50% */
  transform-origin: 0 0; /* 缩放的原点位置，此处为左上角 */
  position: absolute;
  left: 50%;
  top: -80rpx;
  // transform: translate(-50%, -50%);
}

/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
.charts-box {
  width: 100%;
  height: 300px;

  width: 80%;
  height: 300px;
  // transform: translateX(-36.5%) scale(0.7); /* 缩放比例，此处为50% */
  transform: translateX(-43%) scale(0.6); /* 缩放比例，此处为50% */
  transform-origin: 0 0; /* 缩放的原点位置，此处为左上角 */
  position: absolute;
  left: 50%;
  // top: -65rpx;
  // top: -20%;
  top: -38%;
  z-index: -1;
}
</style>
